package com.bwsoft.api.service.impl;

import com.bwsoft.admin.domain.Account;
import com.bwsoft.admin.domain.QualityControl;
import com.bwsoft.admin.domain.QualityControlJoiner;
import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.api.service.QualityControlService;
import com.bwsoft.api.util.Constant;
import com.bwsoft.util.*;
import com.bwsoft.util.ruanweisms.RuanweiSmsUtil;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service(QualityControlService.NAME)
public class QualityControlServiceImpl extends BaseServiceImpl implements QualityControlService{
	private static Logger LOG = Logger.getLogger(QualityControlServiceImpl.class);

	
	/**
	 * 获取质量控制的列表
	 */
	@SuppressWarnings("unchecked")
	@Override
	public ResponsePojo getQualityControlList(String userid, String field,
			String scope, String count, String nature, String search,
			Integer page) {
		ResponsePojo rp = new ResponsePojo();
		// 判断验证码是否正确
		try {
			
			LOG.info("开始查询用户编号为："+userid+"的用户");
			Account account= accountDao.findById(Integer.parseInt( userid));
			
			if (account == null) {
				rp.setErrcode(1);
				rp.setErrmsg("没有 用户编号为："+userid+"的用户");
				return rp;
			}

			StringBuffer selectQCHql=new StringBuffer("from QualityControl as qc where qc.openFlag=true ");
			if(field!=null&&!field.trim().equals("")){
				selectQCHql.append("and qc.field="+field);
			}
			if(scope!=null&&!scope.trim().equals("")){
				selectQCHql.append("and qc.scope="+scope);
			}
			if(count!=null&&!count.trim().equals("")){
				selectQCHql.append("and qc.count="+count);
			}
			if(nature!=null&&!nature.trim().equals("")){
				selectQCHql.append("and qc.standard="+nature);
			}
			if(search!=null&&!search.trim().equals("")){
				selectQCHql.append("and qc.projectName like '%"+search+"%' ");
			}
			selectQCHql.append(" order by qc.addTime desc");
			LOG.info("组装的HQL ：" +selectQCHql);
			
			String pageCount=qualityControlDao.findByHql("select count(*) "+selectQCHql).get(0).toString();
			//List<QualityControl> totalCount=qualityControlDao.findByHql(selectQCHql.toString(), null);
			List<QualityControl> qualityControls=qualityControlDao.findPage(selectQCHql.toString(), Constant.PAGE_COUNT , (page-1)*Constant.PAGE_COUNT, null);
			LOG.info("按照条件可以查出共"+pageCount+"条数据");
			LOG.info("查询出"+qualityControls.size()+"条数据");
			
			String accHql="from QualityControlJoiner as qcj where qcj.joinerId.accountId="+userid;
			
			Map<String ,Object> returnMap=new HashMap();
			returnMap.put("pageNow", page);
			returnMap.put("totalPage", Integer.parseInt(pageCount)/Constant.PAGE_COUNT+1);
			returnMap.put("qualitycontrol", createQualityControl(qualityControls,qualityControlJoinerDao.findByHql(accHql)));
			rp.setErrcode(0);
			rp.setErrmsg("操作成功！");
			rp.setData(returnMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e);
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		return rp;
	}
	
	
	
	private List<Map<String,Object>> createQualityControl(List<QualityControl> qualityControls,List<QualityControlJoiner> joinQcSet){
		List<Map<String,Object>> returnMaps=new ArrayList<Map<String,Object>>();
		Map<String, String> statusMap=dictionaryDataService.getDicDataByName("qc_status");
		Map<String, String> fieldMap=dictionaryDataService.getDicDataByName("qc_field");
		Map<String, String> scopeMap=dictionaryDataService.getDicDataByName("qc_scope");
		Map<String, String> countMap=dictionaryDataService.getDicDataByName("qc_count");
		Map<String, String> natureMap=dictionaryDataService.getDicDataByName("qc_nature");
		for (QualityControl qc : qualityControls) {
			Map<String,Object> stringMap=new HashMap<String, Object>();
			stringMap.put("id", qc.getQcId());
			stringMap.put("projectName", qc.getProjectName());
			stringMap.put("status", qc.getStatus());
			stringMap.put("statusname", statusMap.containsKey(qc.getStatus().toString())?statusMap.get(qc.getStatus().toString()):"" );
			stringMap.put("field", fieldMap.containsKey(qc.getField().toString())?fieldMap.get(qc.getField().toString()):"" );
			stringMap.put("scope", scopeMap.containsKey(qc.getScope().toString())?scopeMap.get(qc.getScope().toString()):"" );
			stringMap.put("count", countMap.containsKey(qc.getCount().toString())?countMap.get(qc.getCount().toString()):"" );
			stringMap.put("nature", natureMap.containsKey(qc.getNature().toString())?natureMap.get(qc.getNature().toString()):"" );
			stringMap.put("openFlag", qc.getOpenFlag());
			stringMap.put("description", qc.getDescription());
			stringMap.put("reportStatus", qc.getReportStatus());
			stringMap.put("isjoin", false);
			for (QualityControlJoiner qcJoin : joinQcSet) {
				if(qc.getQcId().equals(qcJoin.getQualityControl().getQcId())){
					stringMap.put("isjoin", true);
					break;
				}
			}
			returnMaps.add(stringMap);
		}
		
		return returnMaps;
		
	}



	@Override
	public ResponsePojo submitQualityControl(String sponsor,
			String projectName, String field, String scope, String count,
			String standard,String nature, String price,String description, String other, Date beginDate,
			Date feedBackDate, Date endDate, Boolean ptclsj, Boolean gbjgxx,
			Boolean ptxz, File[] img, String[] imgFileName) {
		
		ResponsePojo rp = new ResponsePojo();
		// 判断验证码是否正确
		try {
			
			LOG.info("开始查询用户编号为："+sponsor+"的用户");
			Account account= accountDao.findById(Integer.parseInt( sponsor));
			QualityControl qualityControl=new QualityControl();
			if (account == null) {
				rp.setErrcode(1);
				rp.setErrmsg("没有 用户编号为："+sponsor+"的用户");
				return rp;
			}
			if (dictionaryDataService.getDicValueDataByNameValue("qc_field", field).equals("")) {
				rp.setErrcode(1);
				rp.setErrmsg("名字为qc_field的字典下没有值为："+field+"的字典");
				return rp;
			}
			if (dictionaryDataService.getDicValueDataByNameValue("qc_scope", scope).equals("")) {
				rp.setErrcode(1);
				rp.setErrmsg("名字为qc_scope的字典下没有值为："+scope+"的字典");
				return rp;
			}
			if (dictionaryDataService.getDicValueDataByNameValue("qc_count", count).equals("")) {
				rp.setErrcode(1);
				rp.setErrmsg("名字为qc_count的字典下没有值为："+count+"的字典");
				return rp;
			}
			if (dictionaryDataService.getDicValueDataByNameValue("qc_nature", nature).equals("")) {
				rp.setErrcode(1);
				rp.setErrmsg("名字为qc_nature的字典下没有值为："+nature+"的字典");
				return rp;
			}
			Calendar now = Calendar.getInstance();
			String realpath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_IMG_QUALITYCONTROL+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
			if(img!=null){
			String[] fileName=new String[imgFileName.length] ;
			for(int i=0;i<fileName.length;i++){
				if(imgFileName[i]==null||"".equals(imgFileName[i])) continue;
				fileName[i]=UUID.randomUUID().toString()+imgFileName[i].substring(imgFileName[i].lastIndexOf('.'), imgFileName[i].length());
			}
			UploadFileUtil.uploadFile(fileName, img, realpath);
			qualityControl.setImg1(fileName.length>=1&&fileName[0]!=null&&!"".equals(fileName[0])?Constant.PATH_IMG_QUALITYCONTROL+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+fileName[0]:"");
			qualityControl.setImg2(fileName.length>=2&&fileName[1]!=null&&!"".equals(fileName[1])?Constant.PATH_IMG_QUALITYCONTROL+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+fileName[1]:"");
			qualityControl.setImg3(fileName.length==3&&fileName[2]!=null&&!"".equals(fileName[2])?Constant.PATH_IMG_QUALITYCONTROL+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+fileName[2]:"");
			}
			qualityControl.setSponsor(account);
			qualityControl.setProjectName(projectName);
			qualityControl.setField(Integer.parseInt(field));
			qualityControl.setScope(Integer.parseInt(scope));
			qualityControl.setCount(Integer.parseInt(count));
			qualityControl.setStandard(standard);
			qualityControl.setNature(Integer.parseInt( nature));
			qualityControl.setPrice(price);
			qualityControl.setDescription(description);
			qualityControl.setOther(other);
			qualityControl.setBeginDate(beginDate);
			qualityControl.setFeedBackDate(feedBackDate);
			qualityControl.setEndDate(endDate);
			qualityControl.setPtclsj(ptclsj);
			qualityControl.setGbjgxx(gbjgxx);
			qualityControl.setPtxz(ptxz);
			qualityControl.setStatus(new Date().after(beginDate)?2:1);
			qualityControl.setReportStatus(false);
			qualityControl.setAddTime(new Date());
			qualityControl.setOpenFlag(true);
			Integer qcId=(Integer) qualityControlDao.save(qualityControl);
			
			qualityControl=qualityControlDao.findById(qcId);
			
			rp.setErrcode(0);
			rp.setErrmsg("发起成功！");
			rp.setData(qualityControlInfoMap(qualityControl,sponsor));
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + ExceptionUtil.getErrorInfoFromException(e));
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		return rp;
		
	}
	
	
	
	/**
	 * 得到用户详细信息
	 * @return
	 */
	public Map<String,Object> qualityControlInfoMap(QualityControl qualityControl,String userid){
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("id", qualityControl.getQcId());
		map.put("status", qualityControl.getStatus());
		map.put("statusname", dictionaryDataService.getDicValueDataByNameValue("qc_status", qualityControl.getStatus()));
		Boolean isjoin=false;
		for (QualityControlJoiner qcJoiner : qualityControl.getQualityControlJoiners()) {
			if(qcJoiner.getJoinerId().getAccountId()==Integer.parseInt(userid)){
				isjoin=true;
				break;
			}
		}
		map.put("isjoin", isjoin);
		map.put("sponsorId", qualityControl.getSponsor().getAccountId());
		map.put("sponsorName", qualityControl.getGbjgxx()? qualityControl.getSponsor().getCompName():"");
		map.put("projectName", qualityControl.getProjectName());
		map.put("field",dictionaryDataService.getDicValueDataByNameValue("qc_field", qualityControl.getField()));
		map.put("scope", dictionaryDataService.getDicValueDataByNameValue("qc_scope", qualityControl.getScope()));
		map.put("count", dictionaryDataService.getDicValueDataByNameValue("qc_count", qualityControl.getCount()));
		map.put("nature", dictionaryDataService.getDicValueDataByNameValue("qc_nature", qualityControl.getNature()));
		map.put("standard", qualityControl.getStandard());
		map.put("description", qualityControl.getDescription());
		map.put("price", qualityControl.getPrice());
		map.put("openFlag", qualityControl.getOpenFlag());
		map.put("closeReason", qualityControl.getCloseReason());
		map.put("other", qualityControl.getOther());
		map.put("img1",  qualityControl.getImg1());
		map.put("img2", qualityControl.getImg2());
		map.put("img3", qualityControl.getImg3());
		map.put("beginDate",new SimpleDateFormat("yyyy-MM-dd").format( qualityControl.getBeginDate()));
		map.put("feedBackDate", new SimpleDateFormat("yyyy-MM-dd").format( qualityControl.getFeedBackDate()));
		map.put("endDate", new SimpleDateFormat("yyyy-MM-dd").format( qualityControl.getEndDate()));
		map.put("reportStatus", qualityControl.getReportStatus());
		if(qualityControl.getFile()!=null){
			try {
				map.put("reportName", qualityControl.getFile().getName());
				map.put("reportUrl", "/api/jsp/pdf.jsp?r="+Base64Util.getBase64(DesUtil.encrypt("fileid="+qualityControl.getFile().getId(), Constant.KEY_DES).getBytes("utf-8")));
				map.put("reportSize", qualityControl.getFile().getSize());
			} catch (Exception e) {
				e.printStackTrace();
				LOG.info("组装文件路径异常"+e);
				map.put("reportUrl", "/api/jsp/pdferror.jsp?");
				map.put("reportSize", 0);
				map.put("reportName", "");
			}
		}else{
			map.put("reportUrl", "");
			map.put("reportSize", 0);
			map.put("reportName", "");
		}
		List<Map<String,Object>> joinList=new ArrayList<Map<String,Object>>();
		for (QualityControlJoiner qcj : qualityControl.getQualityControlJoiners()) {
			Map<String,Object> qcjMap=new HashMap<String, Object>();
			qcjMap.put("userId", qcj.getJoinerId().getAccountId());
			qcjMap.put("compName", qcj.getJoinerId().getCompName());
			qcjMap.put("linkMan", qcj.getJoinerId().getLinkMan());
			qcjMap.put("phone", qcj.getJoinerId().getPhone());
			joinList.add(qcjMap);
		}
		map.put("joiner", joinList);
		return map;
	}



	@Override
	public ResponsePojo qualityControlInfo(String userid, String id) {
		
		ResponsePojo rp = new ResponsePojo();
		
		try{
			
			QualityControl qc=qualityControlDao.findById(Integer.parseInt(id));
			
			
			if(qc==null){
				rp.setErrcode(1);
				rp.setErrmsg("没有编号为"+id+"的质量控制！");
				return rp;
			}
			
			
			
			rp.setErrcode(0);
			rp.setErrmsg("请求成功！");
			rp.setData(qualityControlInfoMap(qc,userid));
			
		}catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e.toString());
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		
		return rp;
	}


	/**
	 * 
	 */
	@Override
	public ResponsePojo qualityControlJoinIn(String joiner, String id) {
		ResponsePojo rp = new ResponsePojo();
		
		try{
			LOG.info("开始查询编号为"+id+"的质量控制");
			QualityControl qc=qualityControlDao.findById(Integer.parseInt(id));
			LOG.info("开始查询编号为"+joiner+"的用户");
			Account ac=accountDao.findById(Integer.parseInt(joiner));
			
			if(qc==null){
				rp.setErrcode(1);
				rp.setErrmsg("没有编号为"+id+"的质量控制！");
				return rp;
			}
			
			if(ac==null){
				rp.setErrcode(1);
				rp.setErrmsg("没有编号为"+joiner+"的用户！");
				return rp;
			}
			
			for (QualityControlJoiner qcj : qc.getQualityControlJoiners()) {
				if(qcj.getJoinerId().getAccountId()==Integer.parseInt(joiner)){
					rp.setErrcode(1);
					rp.setErrmsg("编号为"+joiner+"的用户已经参加本次的质量控制！");
					return rp;
				}
			}
			Set<QualityControlJoiner> qualityControlJoiners=qc.getQualityControlJoiners();
			
			QualityControlJoiner qcj=new QualityControlJoiner();
			qcj.setJoinerId(ac);
			qcj.setQualityControl(qc);
			qcj.setAddTime(new Date());
			
			qualityControlJoiners.add(qcj);
			
			qc.setQualityControlJoiners(qualityControlJoiners);
			qualityControlDao.saveOrUpdate(qualityControlDao.getHibernateTemplate().merge( qc));
			
			rp.setErrcode(0);
			rp.setErrmsg("操作成功！");
			
		}catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e.toString());
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		
		return rp;
	}



	@Override
	public ResponsePojo myList(String userid, Boolean canyuFlag, Integer page) {
		ResponsePojo rp = new ResponsePojo();
		// 判断验证码是否正确
		try {
			
			
			LOG.info("开始查询用户编号为："+userid+"的用户");
			Account account= accountDao.findById(Integer.parseInt( userid));
			
			if (account == null) {
				rp.setErrcode(1);
				rp.setErrmsg("没有 用户编号为："+userid+"的用户");
				return rp;
			}
			
			String hql = "";
			if (canyuFlag) {
				hql = "select qc from QualityControl as qc join qc.qualityControlJoiners as qcj where qcj.joinerId.accountId="
						+ userid + " order by qc.addTime desc";
			} else {
				hql = "from QualityControl as qc where qc.sponsor.accountId="
						+ userid + " order by qc.addTime desc";
			}
			
			LOG.info("组装的HQL ：" +hql);
			
			
			List<QualityControl> totalCount=qualityControlDao.findByHql(hql.toString(), null);
			List<QualityControl> qualityControls=qualityControlDao.findPage(hql.toString(), Constant.PAGE_COUNT , (page-1)*Constant.PAGE_COUNT, null);
			LOG.info("按照条件可以查出"+totalCount.size()+"条数据");
			LOG.info("查询出"+qualityControls.size()+"条数据");
			
					
			String accHql="from QualityControlJoiner as qcj where qcj.joinerId.accountId="+userid;
			Map<String ,Object> returnMap=new HashMap();
			returnMap.put("pageNow", page);
			returnMap.put("totalPage", totalCount.size()/Constant.PAGE_COUNT+1);
			returnMap.put("qualitycontrol", createQualityControl(qualityControls,qualityControlJoinerDao.findByHql(accHql)));
			rp.setErrcode(0);
			rp.setErrmsg("操作成功！");
			rp.setData(returnMap);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info("异常" + e);
			rp.setErrcode(50000);
			rp.setErrmsg("服务器异常");
			rp.setData(e.toString());
			return rp;
		}
		return rp;
	}


	/**
	 * Quartz 定时触发 质量控制 反馈前五天会轮询推送消息
	 */
	public void timerInvokingFeedbackPush() throws ParseException {
		
		LOG.info("开始执行定时调度方法：定时推送质量控制的反馈报告结束日期前五天的内容");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		//开始找到所有需要推送的
		String hql="from QualityControl as qc where qc.feedBackDate>=? and qc.feedBackDate<=? and qc.status = 3 and openFlag =1 ";
		Calendar beginCalendar = Calendar.getInstance();
		beginCalendar.add(Calendar.DAY_OF_MONTH, 5);
		Calendar endCalendar = Calendar.getInstance();
		endCalendar.add(Calendar.DAY_OF_MONTH, -1);
		List<QualityControl> qualityControls=qualityControlDao.findByHql(hql,sdf.parse(sdf.format(endCalendar.getTime())),sdf.parse(sdf.format(beginCalendar.getTime())));
		//调用推送方法
		for (QualityControl qualityControl : qualityControls) {
			String text="您的质量控制：{0}，即将到达反馈时间：{1}，请准时提交反馈报告给管理员！";
			String content=MessageFormat.format(text, qualityControl.getProjectName(),new SimpleDateFormat("yyyy-MM-dd").format(qualityControl.getFeedBackDate()));
			String title="U标提醒";
			LOG.info("开始极光推送消息");
			JPushUtil.simplePushMessage(qualityControl.getSponsor().getAccountId().toString(), content);
			LOG.info("开始发送短信");
			String returnMsg=RuanweiSmsUtil.sendQCTipic(qualityControl.getSponsor().getPhone(), content+"【优标检测】");
			LOG.info("发送短信结束返回的报文为："+returnMsg);
		}
		LOG.info("推送结束！");
		
	}
	/**
	 * Quartz 定时触发 质量控制 反馈前五天会轮询推送消息
	 */
	/*public void timerInvokingStatus(){
		
		LOG.info("开始执行定时调度方法：定时更改项目状态");
		
		String changeWeiKaishiHQL="update QualityControl qc set qc.status=2 where qc.status!=2 and qc.beginDate<? and qc.endDate>? and openFlag =1";
		String changeFeedBackHQL="update QualityControl qc set qc.status=3 where qc.status!=3 and qc.endDate<? and qc.feedBackDate>? and openFlag =1";
		String changeEndHQL="update QualityControl qc set qc.status=4 where qc.status!=4 and qc.feedBackDate<? and openFlag = 1";
		Calendar endCalendar = Calendar.getInstance();
		endCalendar.add(Calendar.DAY_OF_MONTH, -1);
		Date beforeDate=endCalendar.getTime();
		Integer changeWeikaishiCount=qualityControlDao.executeByHql(changeWeiKaishiHQL, new Date(),beforeDate);
		LOG.info("将未开始状态改变为正在进行的数量为"+changeWeikaishiCount);
		Integer changeFeedBackCount=qualityControlDao.executeByHql(changeFeedBackHQL, beforeDate,beforeDate);
		LOG.info("将正在进行的状态改变为待反馈的数量为"+changeFeedBackCount);
		//Integer changeEndCount=qualityControlDao.executeByHql(changeEndHQL, beforeDate);
		//LOG.info("将待反馈的状态改变为已结束的数量为"+changeEndCount);
		LOG.info("结束执行定时调度方法：定时更改项目状态！");
		
	}*/

	public void timerInvokingStatus(){
		LOG.info("开始执行定时调度方法：定时更改项目状态");
		//查询全部开启状态的质量控制并且状态 不等于 完成的
		List<QualityControl> qualityControlList = qualityControlDao.findByHql("from QualityControl where openFlag =1 and status !=4");
		for (QualityControl qualityControl : qualityControlList) {
			if(qualityControl.getStatus()==1){
				if(new Date().getTime()>=qualityControl.getBeginDate().getTime()){
					qualityControl.setStatus(2);
					qualityControlDao.update(qualityControl);
					continue;
				}
			}
			if(qualityControl.getStatus()==2){
				if(new Date().getTime()>qualityControl.getEndDate().getTime()){
					qualityControl.setStatus(3);
					qualityControlDao.update(qualityControl);
					continue;
				}
			}
			if(qualityControl.getStatus()==3){
				if(new Date().getTime()>qualityControl.getFeedBackDate().getTime()){
					qualityControl.setStatus(4);
					qualityControlDao.update(qualityControl);
					continue;
				}
			}
		}
		LOG.info("结束执行定时调度方法：定时更改项目状态！");
	}
	

	
}
